package py.com.alfa.escriba.gui.controller.formatter;


import java.text.ParseException;
import java.util.Locale;

import org.springframework.format.Formatter;

import py.com.alfa.escriba.gui.dto.GenericDTO;




public class GenericFormatter implements Formatter<GenericDTO>{

//	private final Logger logger = LoggerFactory.getLogger(GenericFormatter.class);
	
	@Override
	public String print(GenericDTO object, Locale locale) {
		StringBuffer sb = new StringBuffer();
		sb.append(object.getCodigo());
		if(object.getDescripcion() != null){
			sb.append("|").append(object.getDescripcion());
		}
		return sb.toString();
	}

	@Override
	public GenericDTO parse(String text, Locale locale) throws ParseException {
		GenericDTO obj = new GenericDTO();
		if(text.contains("|")){
			String[] split = text.split("\\|");
			obj.setCodigo(split[0]);
			obj.setDescripcion(this.clean(split[1]));			
		}else{
			obj.setCodigo(text);
		}
		return obj;
	}
	
	
	private String clean(String str) {
	     for(int i=0;i<str.length();i++) {
	    	 if( str.charAt(i) != '-') {
	    		 return str.substring(i);
	    	 }
	     }
	     
	     return str;
	}
	
}
